<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no">
    <title>axios demos</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .container {
            padding: 10px 15px;
        }
    </style>
    <script src="https://unpkg.com/axios@0.21.0/dist/axios.js"></script>
</head>
<body>
    <div class="container">
        <h1>axios demo</h1>
        <p>为了能正常使用该样例，需要首先开启本地服务器 <code>anywhere -s</code></p>
        <h2>cancel a request</h2>
        <button onclick="sendRequest()">send request</button>
        <button onclick="cancelRequest()">cancel request</button>
    </div>

    <script>
        const api = './data.json';
        const CancelToken = axios.CancelToken;
        const source = CancelToken.source();

        function sendRequest() {
            console.log('send request');
            axios.get(api, {
                cancelToken: source.token,
            })
                .then(function(res) {
                    debugger;
                    console.log(res);
                })
                .catch(function(thrown) {
                debugger;
                if (axios.isCancel(thrown)) {
                    console.log('Request canceled', thrown.message);
                } else {
                    // handle error
                }
            });
        }

        function cancelRequest() {
            console.log('cancel request');
            source.cancel('Operation canceled by the user.');
        }
    </script>
</body>
</html>
